/*
 * @Author: szx
 * @Date: 2022-06-10 18:51:04
 * @LastEditTime: 2022-06-10 19:36:42
 * @Description:
 * @FilePath: \leetcode\面试题\16\21\21.js
 */
/**
 * @param {number[]} array1
 * @param {number[]} array2
 * @return {number[]}
 */
var findSwapValues = function (array1, array2) {
    const sum1 = array1.reduce((a, b) => a + b);
    const sum2 = array2.reduce((a, b) => a + b);
    const cha = sum1 - sum2;
    if (cha & 1) return [];
    cha = cha / 2;
    for (let i = 0; i < array1.length; i++) {
        const tmp = array1[i] - cha;
        if (array2.includes(tmp)) return [array1[i], tmp];
    }
    return [];
};

var findSwapValues = function (array1, array2) {
    const sum1 = array1.reduce((a, b) => a + b);
    const sum2 = array2.reduce((a, b) => a + b);
    let cha = sum1 - sum2;
    if (cha & 1) return [];
    cha /= 2;
    array1.sort((a, b) => a - b);
    array2.sort((a, b) => a - b);
    const m = array1.length,
        n = array2.length;
    let i = (j = 0);
    while (i < m && j < n) {
        const a = array1[i],
            b = array2[j];
        if (a - b === cha) return [a, b];
        if (a - b > cha) j++;
        else i++;
    }
    if (i === m) {
        const a = array1[m - 1];
        while (j < n) {
            if (a - array2[j] === cha) return [a, array2[j]];
            j++;
        }
    }
    if (j === n) {
        const b = array1[n - 1];
        while (i < m) {
            if (array1[i] - b === cha) return [array1[i], b];
            i++;
        }
    }
    return [];
};

var findSwapValues = function (array1, array2) {
    const sum1 = array1.reduce((a, b) => a + b);
    const sum2 = array2.reduce((a, b) => a + b);
    let cha = sum1 - sum2;
    if (cha & 1) return [];
    cha = cha / 2;
    const set = new Set(array2);
    for (let i = 0; i < array1.length; i++) {
        const tmp = array1[i] - cha;
        if (set.has(tmp)) return [array1[i], tmp];
    }
    return [];
};
// console.log(findSwapValues([519, 886, 282, 382, 662, 4718, 258, 719, 494, 795], [52, 20, 78, 50, 38, 96, 81, 20]));
console.log(findSwapValues([855, 110, 365, 337, 237, 203, 80, 895, 346, 628], [87, 64, 91, 21, 18, 98, 87, 52]));
